package web.admin.shop.category;

import domain.shop.Category;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.panel.EmptyPanel;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.spring.injection.annot.SpringBean;
import service.facade.admin.ShopAdminService;
import web.admin.AdminPage;
import web.eshop.tree.CategoryTreeModelContainer;

import javax.swing.tree.DefaultMutableTreeNode;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * This class provides administration of categories
 */
public final class CategoryAdminPanel extends Panel {


    @SpringBean
    private ShopAdminService shopAdminService;
    private Panel empty = new EmptyPanel("current");
    private Panel current = empty;
    private static Logger logger = Logger.getLogger(CategoryAdminPanel.class.getName());
    AdminPage parent;
    @SpringBean
    CategoryTreeModelContainer modelProvider;

    public CategoryAdminPanel(String id, final AdminPage parent) {
        super(id);
        this.parent = parent;

        this.empty.setOutputMarkupId(true);
        this.empty.setMarkupId("current");

        this.current.setOutputMarkupId(true);
        Form form = new Form("form");
        form.setOutputMarkupId(true);
        add(current);

        Link addCategory = new Link("addCategory") {

            @Override
            public void onClick() {
                Category category = null;
                try {
                    category = shopAdminService.createCategory();
                    DefaultMutableTreeNode node = updateLeftMenuTree(category, parent);
                    replacePanel(node, null);
                    info(getLocalizer().getString("shop.category.add.comleted", CategoryAdminPanel.this));
                } catch (Exception e) {
                    logger.log(Level.SEVERE, null, e);
                    error(getLocalizer().getString("system.error", this));
                }

            }
        };
        form.add(addCategory);
        add(form);
        setOutputMarkupPlaceholderTag(true);


    }

    private DefaultMutableTreeNode updateLeftMenuTree(Category category, AdminPage parent) {
        CategoryLeftMenuAdminPanel panel = (CategoryLeftMenuAdminPanel) parent.getLeftPanel();
        return panel.addNode(null, category);
    }

    public void replacePanel() {
        current.replaceWith(empty);
        current = empty;
    }

    public void replacePanel(DefaultMutableTreeNode node, AjaxRequestTarget target) {
        CategoryPanel categoryPanel = new CategoryPanel("current", node, this);
        current.replaceWith(categoryPanel);
        current = categoryPanel;
        if (target != null) {
            target.addComponent(categoryPanel, "current");
        }
    }

    public AdminPage getAdminPage() {
        return parent;
    }


}
